package edu.sctu.yueding.activitys;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.mobsandgeeks.saripaar.Rule;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.annotation.Required;
import com.mobsandgeeks.saripaar.annotation.TextRule;

import java.util.HashMap;

import edu.sctu.yueding.R;
import edu.sctu.yueding.bean.JsonBaseBeen;
import edu.sctu.yueding.bean.TokenResult;
import edu.sctu.yueding.bean.UserBean;
import edu.sctu.yueding.config.CacheConfig;
import edu.sctu.yueding.config.URLConfig;
import edu.sctu.yueding.utils.JumpUtils;
import edu.sctu.yueding.utils.ProgressUtil;
import edu.sctu.yueding.utils.httputils.GetVolleyHttp;
import edu.sctu.yueding.utils.httputils.SharePreference;

/**
 * Created by fll on 2016/8/3.
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener, Validator.ValidationListener {

    private TextView mRegisterCount;
    private TextView mResetPassword;
    private ImageView mLoginBackButton;
    private Button mLoginButton;

    @Required(order = 1, message = "必填选项！")
    @TextRule(order = 2, minLength = 11, maxLength = 11, message = "请输入正确的电话号码！")
    private EditText mCountEditText;

    @Required(order = 3, message = "必填选项！")
    private EditText mPasswordEditText;


    private SharePreference sharePreference;

    private String username;
    private String password;
    private Bundle bundle;

    private Handler handler = new Handler();
    private ProgressUtil progressUtil;
    private String show = null;
    private ProgressDialog progressDialog;

    private Validator validator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myinfo_login);

        initView();
        setEvent();
        initSystemBarDDrawable(this, R.drawable.overlay);
    }


    private void initView() {

        validator = new Validator(this);
        mCountEditText = (EditText) findViewById(R.id.myinfo_login_edittext_count);

        mPasswordEditText = (EditText) findViewById(R.id.myinfo_login_edittext_password);
        mResetPassword = (TextView) findViewById(R.id.myinfo_reset_password_txt);

        mRegisterCount = (TextView) findViewById(R.id.myinfo_login_register_now);
        mLoginButton = (Button) findViewById(R.id.myinfo_login_button_login);
        mLoginBackButton = (ImageView) findViewById(R.id.myinfo_login_button_back);
        sharePreference = SharePreference.getInstance(this);
        progressUtil = ProgressUtil.getInstance(LoginActivity.this, show);
    }

    private void setEvent() {

        mRegisterCount.setOnClickListener(this);
        mLoginButton.setOnClickListener(this);
        mResetPassword.setOnClickListener(this);
        mLoginBackButton.setOnClickListener(this);
        validator.setValidationListener(this);

    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {

            case R.id.myinfo_login_register_now:
                JumpUtils.jumpActivity(LoginActivity.this, RegisterActivity.class);
                break;
            case R.id.myinfo_login_button_login:

                validator.validate();

                break;
            case R.id.myinfo_reset_password_txt:

                JumpUtils.jumpActivity(LoginActivity.this, ResetPasswordActivity.class);
                break;

            case R.id.myinfo_login_button_back:
                Bundle bundle = new Bundle();
                bundle.putInt("flag", 3);
                JumpUtils.activityToFragmentJump(LoginActivity.this, bundle);
                finish();
                break;
        }

    }


    private void getChatTokenAndConnectRY(String uesrId) {

        GetVolleyHttp.getInstance(this).getStringGETJsonData(URLConfig.getChatToken(uesrId), new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                JsonBaseBeen<TokenResult> t = JSON.parseObject(response, new TypeReference<JsonBaseBeen<TokenResult>>() {
                }.getType());

                if (t.getMeta().code == 200) {

                    Log.e("333333333", t.getData().getToken());
                    sharePreference.setCache(CacheConfig.CHAT_TOKEN, t.getData().getToken());

                    connect(t.getData().getToken());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }, "");

    }


    private void getMyInfo(String token) {

        GetVolleyHttp.getInstance(LoginActivity.this).getStringGETJsonData(URLConfig.USER_INFO, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                Log.e("my", response);

                try {

                    JsonBaseBeen<UserBean> userBeenJsonBaseBeen = JSON.parseObject(response, new TypeReference<JsonBaseBeen<UserBean>>() {
                    }.getType());

                    if (userBeenJsonBaseBeen.getMeta().code == 200) {

                        getChatTokenAndConnectRY(String.valueOf(userBeenJsonBaseBeen.getData().getId()));

                        sharePreference.setCache(CacheConfig.CACHE_PORTRAIT_PATH, userBeenJsonBaseBeen.getData().getAvatarUrl());
                        sharePreference.setCache(CacheConfig.CACHE_USER_ID, userBeenJsonBaseBeen.getData().getId());
                        sharePreference.setCache(CacheConfig.CACHE_NICKNMAE, userBeenJsonBaseBeen.getData().getNickname());
                        sharePreference.setCache(CacheConfig.CACHE_USER_INTRODUCTION_SELF, userBeenJsonBaseBeen.getData().getSelfIntroduction());
                    }
                } catch (ClassCastException e) {

                    Toast.makeText(LoginActivity.this, "网络出了点小问题！", Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }, "Bearer " + token);

    }


    private void startInternet(final String username, final String password) {


        HashMap<String, String> map = new HashMap<String, String>();
        map.put("login", username);
        map.put("password", password);

        GetVolleyHttp.getInstance(LoginActivity.this).getStringPOSTJsonData(URLConfig.LOGIN, map,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Log.e("5555555", response);

                        com.alibaba.fastjson.JSONObject result = JSON.parseObject(response);

                        if (result.getString("access_token") != null) {

                            if (sharePreference.ifHaveShare(CacheConfig.CACHE_USER_NAME) && sharePreference.getString(CacheConfig.CACHE_USER_NAME).equals(username)) {
                                sharePreference.setCache(CacheConfig.IS_EQUALS_USER, true);
                            } else {
                                sharePreference.setCache(CacheConfig.IS_EQUALS_USER, false);
                            }
                            sharePreference.setCache(CacheConfig.IS_UPDATE_PORTRAIT, false);
                            sharePreference.setCache(CacheConfig.CACHE_USER_NAME, username);
                            sharePreference.setCache(CacheConfig.CACHE_USER_PASSWORD, password);
                            sharePreference.setCache(CacheConfig.CACHE_TOKEN, result.getString("access_token"));
                            getMyInfo(result.getString("access_token"));
                            finish();

                            bundle = new Bundle();
                            bundle.putInt("flag", 3);

                            Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();

                            JumpUtils.activityToFragmentJump(LoginActivity.this, bundle);
                            progressUtil.dismiss(progressDialog);

                        } else {

                            JsonBaseBeen<String> jsonBaseBeen = JSON.parseObject(response, new TypeReference<JsonBaseBeen<String>>() {
                            }.getType());
                            Toast.makeText(LoginActivity.this, jsonBaseBeen.getMeta().errorMessage, Toast.LENGTH_SHORT).show();
                            progressUtil.dismiss(progressDialog);
                        }


                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                        Toast.makeText(LoginActivity.this, "网络出了点小问题！", Toast.LENGTH_LONG).show();
                        progressUtil.dismiss(progressDialog);
                    }
                }, CacheConfig.CACHE_INIT_TOKEN);


    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {

            Bundle bundle = new Bundle();
            bundle.putInt("flag", 3);
            JumpUtils.activityToFragmentJump(LoginActivity.this, bundle);
            finish();

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onValidationSucceeded() {

        username = mCountEditText.getText().toString();
        password = mPasswordEditText.getText().toString();

        progressDialog = progressUtil.getProgressDialog(ProgressDialog.STYLE_HORIZONTAL, true);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                startInternet(username, password);
            }
        }, 2000);

    }

    @Override
    public void onValidationFailed(View failedView, Rule<?> failedRule) {

        String message = failedRule.getFailureMessage();

        if (failedView instanceof EditText) {
            failedView.requestFocus();
            ((EditText) failedView).setError(message);
        } else {
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        }
    }
}
